package Api.complaint;

import Util.HttpUtil;
import Util.MyKey;
import Util.SignEncrypt;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.util.encoders.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 投诉记录查询接口
 * 功能：查询指定时间范围内的投诉记录
 */
public class ComplaintRecordQuery {
    // 接口常量定义
    private static final String API_URL = "https://pay.heepay.com/API/Index.aspx";
    private static final String METHOD = "heepay.query.channel.complaint.recordlist";
    private static final String VERSION = "1.0";
    private static final String TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyyMMdd";

    private final String merchId;
    private final PrivateKey privateKey;
    private final SignEncrypt signEncrypt;

    /**
     * 构造方法
     * @param merchId 商户ID
     * @param privateKey 私钥对象
     */
    public ComplaintRecordQuery(String merchId, PrivateKey privateKey) {
        this.merchId = Objects.requireNonNull(merchId, "商户ID不能为空");
        this.privateKey = Objects.requireNonNull(privateKey, "私钥不能为空");
        this.signEncrypt = new SignEncrypt();
    }

    /**
     * 默认构造方法，使用配置的商户信息
     */
    public ComplaintRecordQuery() throws Exception {
        this("1664502", loadPrivateKey(MyKey.privateKeystr));
    }

    /**
     * 加载私钥
     * @param privateKeyStr 私钥字符串
     * @return 私钥对象
     */
    private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
        if (privateKeyStr == null || privateKeyStr.trim().isEmpty()) {
            throw new IllegalArgumentException("私钥字符串不能为空");
        }
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] privateKeyBytes = Base64.decode(privateKeyStr.getBytes());
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
    }

    /**
     * 查询投诉记录
     * @param complaintBeginTime 投诉开始时间(yyyyMMdd)
     * @param complaintEndTime 投诉结束时间(yyyyMMdd)
     * @return 接口返回结果
     */
    public String queryComplaintRecords(String complaintBeginTime, String complaintEndTime) throws Exception {
        // 参数校验
        validateDateParameters(complaintBeginTime, complaintEndTime);

        // 构建业务参数
        JSONObject bizContent = buildBizContent(complaintBeginTime, complaintEndTime);

        // 生成时间戳
        String timestamp = new SimpleDateFormat(TIMESTAMP_FORMAT).format(new Date());

        // 构建签名串
        String signSource = buildSignSource(bizContent, timestamp);

        // 生成签名
        String sign = signEncrypt.sign(signSource, privateKey);

        // 构建请求参数
        JSONObject requestParam = buildRequestParam(bizContent, timestamp, sign);

        // 发送请求
        return sendRequest(requestParam);
    }

    /**
     * 验证日期参数
     */
    private void validateDateParameters(String beginTime, String endTime) {
        if (beginTime == null || !beginTime.matches("\\d{8}")) {
            throw new IllegalArgumentException("投诉开始时间格式错误，应为yyyyMMdd");
        }
        if (endTime == null || !endTime.matches("\\d{8}")) {
            throw new IllegalArgumentException("投诉结束时间格式错误，应为yyyyMMdd");
        }
        if (beginTime.compareTo(endTime) > 0) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }
    }

    /**
     * 构建业务参数
     */
    private JSONObject buildBizContent(String beginTime, String endTime) {
        JSONObject bizContent = new JSONObject();
        bizContent.put("complaint_begin_time", beginTime);
        bizContent.put("complaint_end_time", endTime);
        return bizContent;
    }

    /**
     * 构建签名源字符串
     */
    private String buildSignSource(JSONObject bizContent, String timestamp) {
        return "biz_content=" + bizContent
                + "&merch_id=" + merchId
                + "&method=" + METHOD
                + "&timestamp=" + timestamp
                + "&version=" + VERSION;
    }

    /**
     * 构建完整请求参数
     */
    private JSONObject buildRequestParam(JSONObject bizContent, String timestamp, String sign) {
        JSONObject param = new JSONObject();
        param.put("method", METHOD);
        param.put("version", VERSION);
        param.put("merch_id", merchId);
        param.put("timestamp", timestamp);
        param.put("biz_content", bizContent);
        param.put("sign", sign);
        return param;
    }

    /**
     * 发送请求
     */
    private String sendRequest(JSONObject requestParam) throws Exception {
        String requestJson = requestParam.toString();
        System.out.println("发送请求参数：" + requestJson);
        return HttpUtil.sendJsonHttpPost(API_URL, requestJson);
    }

    public static void main(String[] args) {
        try {
            // 创建查询实例
            ComplaintRecordQuery query = new ComplaintRecordQuery();

            // 设置查询时间范围
            String beginTime = "20250709";
            String endTime = "20250809";

            // 执行查询
            String result = query.queryComplaintRecords(beginTime, endTime);

            // 输出结果
            System.out.println("接口返回结果：" + result);

        } catch (IllegalArgumentException e) {
            System.err.println("参数错误：" + e.getMessage());
        } catch (Exception e) {
            System.err.println("查询失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
